package org.seamon.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.seamon.management.mapper.UserRoleMapper;
import org.seamon.management.pojo.dto.UserRoleInsertDto;
import org.seamon.management.pojo.entity.UserRole;
import org.seamon.management.service.UserRoleService;
import org.seamon.management.util.CacheConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author Simon
* @description 针对表【sys_user_role(用户角色关联表)】的数据库操作Service实现
* @createDate 2025-07-11 00:31:54
*/
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements UserRoleService{

    @Override
    @Cacheable(cacheNames = {CacheConstants.USER_ROLE_LIST}, key = "#dto.userId")
    public void saveRole(UserRoleInsertDto dto) {
        UserRole userRole = new UserRole();
        BeanUtils.copyProperties(dto, userRole);
        this.save(userRole);
    }

    @Override
    @CacheEvict(cacheNames = {CacheConstants.USER_ROLE_LIST}, key = "#userRoleById")
    public void removeUserRoleById(Long userRoleById) {
        this.removeById(userRoleById);
    }

    @Override
    @Cacheable(cacheNames = {CacheConstants.USER_ROLE_LIST}, key = "#userId")
    public List<Long> getRole(Long userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        List<UserRole> roleList = this.list(queryWrapper);
        return roleList.stream()
                .map(UserRole::getRoleId)
                .distinct()
                .toList();
    }
}




